/*
 * @Author: 
 * @Date: 2024-06-12 15:31:06
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-06-18 10:54:54
 * @Description: 
 */
import { Provide, Singleton } from '@midwayjs/decorator';

@Provide()
@Singleton() // 确保服务是单例模式
export class PromiseService {
  private resolveMap: Map<string, () => void> = new Map();

  // 创建一个 promise 并将 resolve 函数存储在 map 中
  public createPromise(id: string): Promise<void> {
    return new Promise<void>((resolve) => {
      this.resolveMap.set(id, resolve);
      console.log(this.resolveMap); // 显示当前 map 的状态
    });
  }

  // 通过 id 解析对应的 promise
  public resolvePromise(id: string): void {
    const resolveFunction = this.resolveMap.get(id);
    console.log(id+'----------------')
    console.log(this.resolveMap);
    if (resolveFunction) {
      resolveFunction(); // 执行 resolve 函数，解析 promise
      this.resolveMap.delete(id); // 从 map 中删除条目
    }
    console.log(this.resolveMap); // 显示 map 的状态，以便检查条目是否已删除
  }
}
